package sk.fiit.icp.data;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class EventsDaoImpl implements EventsDao {
	private HibernateTemplate hibernateTemplate;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
	
	
	@Transactional(readOnly = false)
	public void persist(Events e) {
		hibernateTemplate.merge( "Events", e );
	}

	@Transactional
	public Events findById(int id) {
		@SuppressWarnings("unchecked")
		List<Events> events = hibernateTemplate.find( "from Events AS e fetch all properties WHERE e.idevent = ?", id );
		return (Events) (events.isEmpty()?null:events.get( 0 ));
	}

	@Transactional
	public List<Events> findAllByUser(Users user) {
		return hibernateTemplate.find( "from Events AS e fetch all properties WHERE e.users = ?", user );
	}
	
	@Transactional
	public int remove(int id) {
		return hibernateTemplate.bulkUpdate( "delete from Events AS e WHERE e.idevent = ?", id );
		
	}

	@Transactional(readOnly = false)
	public void update(Events e) {
		hibernateTemplate.merge( "Events", e );
	}


	@SuppressWarnings("unchecked")
	public List<Events> findByUserAndParentEvent(Users user, Events events) {
		return hibernateTemplate.findByNamedParam("from Events ", new String[] {"users","parentEvents"}, new Object[] {user,events});
	}

}
